<template>
  <el-dialog title="登录" :visible.sync="loginFormVisible" width="30%" center top="25vh" :close-on-click-modal="false">
    <el-form size="medium" :model="form" :rules="rules" ref="form">
      <el-form-item label="用户名" prop="userName">
        <el-input v-model="form.userName" placeholder="请输入用户名"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="form.password" placeholder="请输入密码" show-password></el-input>
      </el-form-item>
      <el-form-item>
        <el-button size="medium" type="primary" @click="login">登录</el-button>
        <el-button size="medium" @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
export default {
  data() {
    return {
      form: {
        userName: "",
        password: ""
      },
      rules: {
        userName: [
          {required: true, message: "请输入用户名", trigger: "blur"}
        ],
        password: [
          {required: true, message: "请输入密码", trigger: "blur"}
        ]
      },
      loginFormVisible: false
    }
  },
  methods: {
    showLoginForm() {
      this.loginFormVisible = true;
    },
    login() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.$axios.post("/api/user/login", this.form).then(res => {
            if (res.code === 0) {
              this.$message.success("登录成功");
              this.$emit("success-login");
              this.loginFormVisible = false;
            }
            else {
              if (res.discription !== "") {
                this.$message.error(res.message + "，" + res.description);
              } else {
                this.$message.error(res.message);
              }
            }
          }).catch(err => {
            this.$message.error("登录失败");
          });
        }
        else {
          this.$message.error("输入内容有误");
        }
      });
    },
    resetForm() {
      this.$refs.form.resetFields();
    },
  },
  mounted() {
    document.body.appendChild(this.$el);
  },
  beforeDestroy() {
  },
  destroyed() {
    if (this.$el && this.$el.parentNode) {
      this.$el.parentNode.removeChild(this.$el);
    }
  }
}
</script>

<style scoped lang="scss">

</style>